//
//  UploadPhotosViewController.m
//  DataStatistics
//
//  Created by oilklenze on 16/2/2.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "CommentsViewController.h"
#import "MBProgressHUD.h"
#import "QBImagePickerController.h"
#import "UploadPhotosViewController.h"
#import "CoverView.h"
#define CONTENT_CHARACTER_LIMIT 300

#define kHZMaxLength 100


@interface UploadPhotosViewController () <  UIImagePickerControllerDelegate,
                                             UINavigationControllerDelegate,
                                            QBImagePickerControllerDelegate,
                                                        UIAlertViewDelegate,
                                                        UITextViewDelegate>

{
    BOOL firstPlay; //判断what's on yout mind是否消失
    MBProgressHUD* HUD;
    BOOL breakNetwork; //离开页面中断上传进程
//    UIAlertController *authorizationAlert;//授权提示框
    
    NSRange _currentRange;
    NSRange _deleteRange;
    UITextRange * _textRange;
    
    NSInteger _inputLocation;
    NSInteger _inputLength;
    DevicesWelcome *DevicesView;
    NSInteger j;
    NSString *key;
    CoverView *cover;
}

@property (weak, nonatomic) IBOutlet UILabel *SurplusLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *Label_w;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *Label_W1;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *Label_H;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *talkContentText_H;
@property (weak, nonatomic) IBOutlet UIBarButtonItem* send;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray* addpotos;
@property (strong, nonatomic) IBOutlet UITextView* talkContentText;
@property (strong, nonatomic) NSMutableArray* imgae; //button显示照片
@property (strong, nonatomic) NSMutableArray* assetsOrimage; //上传照片数据 数组里面为id类型
@property (nonatomic) NSInteger pickImageCount;
@end

@implementation UploadPhotosViewController
@synthesize imgae = _imgae;

#pragma mark - 生命周期
- (void)viewDidLoad
{
    [super viewDidLoad];
//    [self welcome];
    
    firstPlay                                = YES;
    breakNetwork                             = NO;
    [self updataUI];
    
    
self.talkContentText.returnKeyType=UIReturnKeyDone;


    
    NSMutableAttributedString* mind = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"What’s on your mind……", "说点什么")
                                                                             attributes:@{
                                                                                 NSForegroundColorAttributeName : RGB(151, 151, 151, 1)
                                                                                        }];
    [self.talkContentText setAttributedText:mind];
    self.talkContentText.delegate            = self;
    [self.send setEnabled:NO];
    
    
    NSLog(@"屏幕宽度 = ========== %f",self.view.bounds.size.width);
    NSLog(@"屏幕高度 = ========== %f",self.view.bounds.size.height);

    

//    
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
//                                                name:@"UITextFieldTextDidChangeNotification"
//                                              object:self.talkContentText];
//    
    
    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeMode:) name:@"UITextInputCurrentInputModeDidChangeNotification" object:nil];

    
}





- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
- (void)updateViewConstraints
{
    [super updateViewConstraints];
    if (SCREEN_HEIGHT == 480) {
        self.talkContentText_H.constant = 128;
        
    }else if (SCREEN_HEIGHT == 667){
        self.talkContentText_H.constant = 200;
        self.Label_H.constant = 200;

    }else if (SCREEN_HEIGHT == 736){
        self.talkContentText_H.constant = 250;
        self.Label_H.constant = 250;

    }else if (SCREEN_HEIGHT == 568){
        self.Label_H.constant = 158;

    }
    
    if (SCREEN_WIDTH == 414){
        self.Label_w.constant = 20;
        self.Label_W1.constant = 20;
    }
}


-(void)welcome
{
    cover = [[CoverView alloc]init];
    
    [cover setCoverObjectForKey:key = @"UploadPhotosView"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapView)];
    
    [cover.DevicesView addGestureRecognizer:tap];
}


-(void)TapView
{
    [cover.DevicesView removeFromSuperview];
    
    [[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:key];
    
}





#pragma mark - 重写方法
//关闭键盘
- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event
{

    [self.view endEditing:YES];
}

#pragma mark - custom methon
- (void)updataUI

{
    for (int i = 0; i < self.addpotos.count; i++) {
        if (i != 0) {
            [self.addpotos[i] setHidden:YES];
        }
        else {
            [self.addpotos[i] setImage:nil forState:UIControlStateNormal];
        }
    }
    //安全起见判断bug
    if (self.imgae.count > 8) {
//        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"super big BUG"
//                                                        message:@"oh my god I'm died"
//                                                       delegate:nil
//                                              cancelButtonTitle:@"die"
//                                              otherButtonTitles:nil, nil];
////        [alert show];
//        //        正文
    }
    else {
        for (int i = 0; i < self.imgae.count; i++) {
            [self.addpotos[i] setHidden:NO];
            [self.addpotos[i] setBackgroundImage:self.imgae[i] forState:UIControlStateNormal];
            [self.addpotos[i] setImage:[UIImage imageNamed:@"删除上传图"] forState:UIControlStateNormal];
            [self.addpotos[i] setHidden:NO];
        }
        if (self.imgae.count != 8) {
            UIButton* button = self.addpotos[self.imgae.count];
            [button setHidden:NO];
            [button setBackgroundImage:[UIImage imageNamed:@"添加上传图-off"] forState:UIControlStateNormal];
            [button setImage:nil forState:UIControlStateNormal];
        }
    }
}

//保存照片 sel方法
- (void)thisImage:(UIImage*)image hasBeenSavedInPhotoAlbumWithError:(NSError*)error usingContextInfo:(void*)ctxInfo
{
    //提取刚保存的PHAsset
    PHFetchOptions* options          = [[PHFetchOptions alloc] init];
    options.sortDescriptors          = @[ [NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES] ];
    PHFetchResult* asssetFetchResult = [PHAsset fetchAssetsWithOptions:options];
    PHAsset* asset                   = [asssetFetchResult lastObject];
    [self.imgae addObject:image];
    [self.assetsOrimage addObject:asset];
    self.imgae = self.imgae;
    if (error) {
//        UIAlertView* aler = [[UIAlertView alloc] initWithTitle:nil
//                                                       message:NSLocalizedString(@"Unable to access photo album", "无法访问相册")
//                                                      delegate:nil
//                                             cancelButtonTitle:@"OK"
//                                             otherButtonTitles:nil, nil];
//        [aler show];
    }
    else {
    }
}
#pragma mark  - 上传数据 - 照片
- (void)updateImage:(NSMutableArray*)imageParameter
{
    //如果不中断网络就上传
    if (!breakNetwork) {
        self.talkContentText.text = [self.talkContentText.text removeEmoji];
//        self.showimage(imageParameter, self.talkContentText.text);
       [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        NSString* url = @"messages/publishMessage.asp";
        url = [IPHEAD stringByAppendingString:url];
        
        
        NSDictionary* parameter;
        if (self.uploadPhotosDeviceCode == nil) {
          parameter = @{ @"content" : self.talkContentText.text,@"publishType" : @1};
        }else {
            parameter = @{ @"content" : self.talkContentText.text,@"publishType" : @1,
                                    @"deviceNo":self.uploadPhotosDeviceCode};
        }
        
        
        NSMutableURLRequest* request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"
                                                                                                  URLString:url
                                                                                                 parameters:parameter
                                                                                  constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            //参数name：是后台给你的图片在服务器上字段名;
            //参数fileNmae：自己起得一个名字，
            //参数mimeType：这个是决定于后来接收什么类型的图片，接收的时png就用image/png ,接收的时jpeg就用image/jpeg
            int i = 0;
            for (UIImage* image in imageParameter) {
                NSData* imageData          = UIImageJPEGRepresentation(image, 0.5);
                NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat       = @"yyyy-MM-dd HH:mm:ss:SSS";
                NSString* fileName = [NSString stringWithFormat:@"%@%@.JPEG", [formatter stringFromDate:[NSDate date]], @(i)];
                
                [formData appendPartWithFileData:imageData
                                            name:@"images"
                                        fileName:fileName
                                        mimeType:@"image/JPEG"];
                i++;
                

                }
            }
                                           error:nil];
        
        
        
        
        AFURLSessionManager* manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

        //设置服务器返回内容的接受格式
        AFHTTPResponseSerializer* responseSer = [AFHTTPResponseSerializer serializer];
        responseSer.acceptableContentTypes    = [NSSet setWithObjects:@"text/html", nil];
        manager.responseSerializer            = responseSer;
        NSProgress* progress                  = nil;
        NSURLSessionUploadTask* uploadTask    = [manager uploadTaskWithStreamedRequest:request
                                                                              progress:&progress
                                                                     completionHandler:^(NSURLResponse* response, id responseObject, NSError* error) {
                                                   
                                                                         NSLog(@"设置服务器返回内容的接受格式 ==============  %@",responseObject);
                                                                         
                [MBProgressHUD hideHUDForView:self.view animated:YES];
           if (error) {
             // NSLog(@"Error: %@", error);
             if (error.code == -1004) {
                   [MBProgressHUD showError:NET_ERROR];
               }else{
                 UIAlertView* aler = [[UIAlertView alloc] initWithTitle:nil
                                                                  message:[NSString stringWithFormat:NSLocalizedString(@"Send failed", "发送失败")]
                                                                 delegate:nil
                                                        cancelButtonTitle:@"OK"
                                                        otherButtonTitles:nil, nil];
                 [aler show];
             }
           }else {
               [MBProgressHUD showSuccess:nil];
               self.updateImageSuccess();
               [self.navigationController popViewControllerAnimated:YES];
               self.send.enabled = YES;
            }
        }];
        [uploadTask resume];
    }
}


#pragma mark - linkUI方法。
- (IBAction)addPotos:(UIButton*)sender
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    //    添加头像
    if (!sender.currentImage) {
        
        
        NSLog(@"添加图像");
        QBImagePickerController* imageMultipleimagesController = [QBImagePickerController new];
        imageMultipleimagesController.mediaType                = QBImagePickerMediaTypeImage;
        imageMultipleimagesController.assetCollectionSubtypes  = @[ @(PHAssetCollectionSubtypeSmartAlbumUserLibrary) ];
        imageMultipleimagesController.delegate                    = self;
        imageMultipleimagesController.allowsMultipleSelection     = YES;
        imageMultipleimagesController.maximumNumberOfSelection    = self.pickImageCount;
        imageMultipleimagesController.showsNumberOfSelectedAssets = YES;
        UIImagePickerController* imagePicker                      = [[UIImagePickerController alloc] init];
        imagePicker.delegate                                      = self;

        UIAlertController* alerController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Choose photos", nil)
                                                                                message:nil
                                                                         preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel",nil)
                                                               style:UIAlertActionStyleCancel
                                                             handler:nil];
        
        UIAlertAction* camera = [UIAlertAction actionWithTitle:NSLocalizedString(@"Take Photo", nil)
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction* _Nonnull action) {
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//          判断是否允许使用相机
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    [self presentViewController:imagePicker animated:YES completion:nil];
                    
                }else{
                    UIAlertController *aler=[UtilToolsClss addAlertControllerForAuthorizationStatus:NSLocalizedString(@"请打开系统设置中\"隐私->相机\",允许\"Oilklenze\"使用您的相机", nil)];
                    [self presentViewController:aler animated:YES completion:nil];
                }
            }];
            
        }];
        
        UIAlertAction* PhotoLibrary = [UIAlertAction actionWithTitle:NSLocalizedString(@"Choose from Photos", nil)
                                                               style:UIAlertActionStyleDefault
                                                             handler:^(UIAlertAction* _Nonnull action) {
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (status == PHAuthorizationStatusDenied) {
                    UIAlertController *aler=[UtilToolsClss addAlertControllerForAuthorizationStatus:NSLocalizedString(@"请打开系统设置中\"隐私->照片\",允许\"Oilklenze\"使用您的照片", nil)];
                    [self presentViewController:aler animated:YES completion:nil];
                }else{
                    [self presentViewController:imageMultipleimagesController animated:YES completion:nil];
                }
                
            }];
        }];
        alerController.title = nil;
        [alerController addAction:cancelAction];
        [alerController addAction:camera];
        [alerController addAction:PhotoLibrary];
        [self presentViewController:alerController animated:YES completion:nil];

        //      删除图像
    }
    else {
        NSLog(@"删除头像");
        [self.imgae removeObject:self.imgae[sender.tag]];
        [self.assetsOrimage removeObjectAtIndex:sender.tag];
        self.imgae = self.imgae;
    }

    
}


- (IBAction)popView:(UIBarButtonItem*)sender
{
    UITextView *textView =nil;
    [self textViewShouldBeginEditing:textView];
    if (![self.talkContentText.text isEqualToString: @""] || self.imgae.count!=0) {
            UIAlertView* aler = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Discard the changes?", nil)
                                                       message:@""
                                                      delegate:self
                                             cancelButtonTitle:NSLocalizedString( @"Cancel", nil)
                                             otherButtonTitles:NSLocalizedString(@"Leave", nil), nil];
            [aler show];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
        breakNetwork = YES;
    }
}

- (IBAction)send:(id)sender
{
    if (self.imgae.count ==0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"请选择照片", nil) message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return ;
    }
    if (firstPlay) {
        self.talkContentText.text = nil;
        firstPlay = NO;
    }
    self.send.enabled = NO;
    HUD ? nil : (HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view]);
    [self.view addSubview:HUD];

    // Set determinate mode
    HUD.mode = MBProgressHUDModeDeterminate;

    //    HUD.delegate = self;
    HUD.labelText = NSLocalizedString(@"Syncing Photos...", nil);
    __block BOOL first = YES;

    // myProgressTask uses the HUD instance to update progress
    //    [HUD showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];
    NSMutableArray* imageParameter = [[NSMutableArray alloc] init];
    for (int i = 0; i < self.assetsOrimage.count; i++) {
        id asset = self.assetsOrimage[i];
        if ([asset isKindOfClass:[PHAsset class]]) {
            PHImageRequestOptions* options = [[PHImageRequestOptions alloc] init];
            options.progressHandler = ^(double progress, NSError* __nullable error, BOOL* stop, NSDictionary* __nullable info) {
                if (HUD.progress <= progress && progress < 1.0) {
                    HUD.progress = progress;
                }
                if (first) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [HUD show:YES];
                    });

                    first = NO;
                }
            };
            options.deliveryMode         = PHImageRequestOptionsDeliveryModeFastFormat;
            options.synchronous          = NO;
            options.networkAccessAllowed = YES;
            PHImageManager* manger       = [PHImageManager defaultManager];
            [manger requestImageForAsset:asset
                              targetSize:PHImageManagerMaximumSize
                             contentMode:PHImageContentModeDefault
                                 options:options
                           resultHandler:^(UIImage* _Nullable result, NSDictionary* _Nullable info) {
                if (result) {
                    [imageParameter addObject:result];
                    if (imageParameter.count == self.assetsOrimage.count) {
                        [HUD hide:YES];
                        [self updateImage:imageParameter];

                        NSLog(@"imageParameter ============== %@",imageParameter);
                        
                    }
                }
            }];
        }
        
        else {
            NSData* imageData = UIImageJPEGRepresentation(asset, 0.5);
            [imageParameter addObject:imageData];
        }
    }

    if (self.assetsOrimage.count == 0) {
        [self updateImage:nil];
    }
}

#pragma mark - 代理方法
#pragma mark UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView*)textView
{
    if (firstPlay) {
        self.talkContentText.text = nil;
        firstPlay = NO;
        [self.talkContentText setTextColor:[UIColor whiteColor]];
    }
    return YES;
}



-(void) changeMode:(NSNotification *)notification{
    NSLog(@"%@",[[UITextInputMode currentInputMode] primaryLanguage]);
}


//限制中英输入法字节
- (void)textViewDidChange:(UITextView *)textView
{
    //    UITextInputMode *mode = [[UITextInputMode activeInputModes] firstObject];
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage];//当前的输入模式
    if ([lang isEqualToString:@"zh-Hans"])
    {
        //        如果输入有中文，且没有出现文字备选框就对字数统计和限制
        //        出现了备选框就暂不统计
        UITextRange *range = [textView markedTextRange];
        
        UITextPosition *position = [textView positionFromPosition:range.start offset:0];
        
        if (!position)
        {
            [self checkText:textView];
        }
    }
    else
    {
        [self checkText:textView];
    }
}

- (void)checkText:(UITextView *)textView
{
    NSString *string = textView.text;
    
    if (string.length > 250)
    {
        
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示",nil) message:NSLocalizedString(@"最多输入250个字符",nil) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定",nil) style:UIAlertActionStyleDefault handler:nil];
        
        [alert addAction:action];
        
        [self presentViewController:alert animated:YES completion:nil];
        
//        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:@"最多输入250个字符" toView:nil];

        
        textView.text = [string substringToIndex:250];
    }
    
    NSInteger length = textView.text.length;
    NSInteger num = 250 - length;
    num = MAX(num, 0);
    
    self.SurplusLabel.text = [NSString stringWithFormat:@"%ld / 250",num];
}




#pragma mark QBImagePickerControllerDelegate

- (void)qb_imagePickerController:(QBImagePickerController*)imagePickerController didFinishPickingAssets:(NSArray*)assets

{
    //提前略缩图
    for (PHAsset* asset in assets){
        PHImageRequestOptions* option = [[PHImageRequestOptions alloc] init];
        //        option.deliveryMode=PHImageRequestOptionsDeliveryModeFastFormat;
        //        option.resizeMode=PHImageRequestOptionsResizeModeFast;
        option.version              = PHImageRequestOptionsVersionCurrent;
        option.networkAccessAllowed = NO;
        option.synchronous          = NO;
        PHImageManager* imageManage = [PHImageManager defaultManager];
        option.progressHandler = ^(double progress, NSError* __nullable error, BOOL* stop, NSDictionary* __nullable info) {
        };
        [imageManage requestImageForAsset:asset
                               targetSize:CGSizeMake(80, 80)
                              contentMode:PHImageContentModeDefault
                                  options:option
                            resultHandler:^(UIImage* _Nullable result, NSDictionary* _Nullable info) {
            if (result) {
                [self.imgae addObject:result];
                self.imgae = self.imgae;
            }

        }];
        //添加asset
        [self.assetsOrimage addObject:asset];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}





- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController*)imagePickerController
{
    [self dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString*, id>*)info
{
    UIImage* theImage = [info valueForKey:UIImagePickerControllerOriginalImage];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        //储存在手机库
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        //判断权限
            if (status == PHAuthorizationStatusDenied) {
                UIAlertController *aler=[UtilToolsClss addAlertControllerForAuthorizationStatus:NSLocalizedString(@"请打开系统设置中\"隐私->照片\",允许\"Oilklenze\"使用您的照片", nil)];
                [self presentViewController:aler animated:YES completion:nil];
            }else{
                SEL selectorToCall = @selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:);
                UIImageWriteToSavedPhotosAlbum(theImage, self, selectorToCall, NULL);
            }
        }];
    };
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    同步后上传中断退出
    if (buttonIndex == 1) {
        [self.navigationController popViewControllerAnimated:YES];
        breakNetwork = YES;
    }
}

#pragma mark - getter and setter method
- (NSMutableArray*)imgae
{
    if (!_imgae) {
        _imgae = [[NSMutableArray alloc] init];
    }
    return _imgae;
}


- (void)setImgae:(NSMutableArray*)imgae
{
    _imgae = imgae;
    self.send.enabled = imgae.count != 0;
    [self updataUI];
}


- (NSInteger)pickImageCount
{
    if (self.imgae.count > 8) {
        _pickImageCount = 0;
    }
    else {
        _pickImageCount = 8 - self.imgae.count;
    }
    return _pickImageCount;
}


- (NSMutableArray*)assetsOrimage
{
    if (!_assetsOrimage) {
        _assetsOrimage = [[NSMutableArray alloc] init];
    }
    return _assetsOrimage;
}


- (UITextView *)talkContentText
{
    _talkContentText.font = [UIFont systemFontOfSize:16];
    return _talkContentText;
}


@end
